import { RingBuffer } from './ring-buffer'

export class History<T> {
  private idx = -1
  private buffer: RingBuffer<T>

  constructor(capacity: number) {
    this.buffer = new RingBuffer<T>(capacity)
  }

  public back(): T | undefined {
    if (this.idx <= 0) {
      this.idx = 0
      return undefined
    }
    this.idx--
    return this.buffer.get(this.idx)
  }

  public forward(): T | undefined {
    const { idx, buffer } = this
    const size = buffer.length
    if (idx >= size - 1) {
      this.idx = size - 1
      return undefined
    }
    this.idx++
    return buffer.get(this.idx)
  }

  public current(): T | undefined {
    return this.buffer.get(this.idx)
  }

  public push(e: T) {
    const cur = this.current()
    if (cur && cur === e) {
      return
    }
    const { idx, buffer } = this
    if (idx < buffer.length - 1) {
      buffer.truncate(this.idx + 1)
    }
    buffer.push(e)
    this.idx = buffer.length - 1
  }
}
